<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>03-渲染器</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      html,
      body {
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
    </style>
  </head>
  <body>
    <script type="module">
      // 引入three.js
      import * as THREE from "three";

      //创建场景
      const scene = new THREE.Scene();

      //创建相机
      const camera = new THREE.PerspectiveCamera(
        45,
        window.innerWidth / window.innerHeight,
        0.1,
        1000
      );
      //设置相机位置
      camera.position.set(0, 200, 10); //统一设置
      //设置相机朝向点位
      camera.lookAt(0, 0, 0);

      //创建渲染器
      const renderer = new THREE.WebGLRenderer({
        antialias: true, //减少边缘齿轮
      });
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);
      //网格
      const gridHelper = new THREE.GridHelper(100, 10, 0xffffff);
      scene.add(gridHelper);

      //创建物体
      const cube = new THREE.Mesh(
        new THREE.BoxGeometry(10, 10, 10),
        new THREE.MeshBasicMaterial({
          color: 0xff11ff,
        })
      );
      scene.add(cube); //在场景中添加物体

      //渲染
      renderer.render(scene, camera);

      //动画函数
      function animate() {
        requestAnimationFrame(animate);
        renderer.render(scene, camera);
      }
      animate();

      let isDown = false;
      let startx = 0;
      let currentX = 0; //记录移动的距离
      //监听鼠标事件
      renderer.domElement.addEventListener("mousedown", (e) => {
        isDown = true;
        startx = e.clientX;
      });
      renderer.domElement.addEventListener("mousemove", (e) => {
        if (isDown) {
          const distanceX = e.clientX - startx;
          currentX += distanceX * 0.01;
          startx = e.clientX;
          const radius = 40;
          camera.position.x = radius * Math.cos(currentX);
          camera.position.z = radius * Math.sin(currentX);
          camera.lookAt(0, 0, 0);
        }
      });
      renderer.domElement.addEventListener("mouseup", (e) => {
        isDown = false;
      });
    </script>
  </body>
</html>
